<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">
          {{getTitleByName(nameOfPermission)}}列表查询
          <el-button link @click="delFav()" style="margin-bottom: 5px;" v-if="userFavorites?.length > 0">
            <svg-icon icon-class="stars" color="#E6A23C" />
          </el-button>
          <el-button link @click="addFav()" style="margin-bottom: 5px;" v-else>
            <svg-icon icon-class="star" />
          </el-button>
        </div>
        <div>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
        </div>
      </el-col>
    </el-row>
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item prop="catalogId" label="项目分类">
          <el-select v-model="listQuery.catalogId" class="m-2" placeholder="请选择" clearable filterable>
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in catalogList" :key="item.id" :label="`${item.catalogCode} - ${item.catalogName}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="code" label="一级项目编号">
          <InputTagDialog v-model="listQuery.code" placeholder="一级项目编号" title="填写一级项目编号" />
        </el-form-item>
        <el-form-item prop="name" label="一级项目名称">
          <el-input v-model="listQuery.name" placeholder="一级项目名称" />
        </el-form-item>
        <el-form-item prop="departmentId" label="编报部门">
          <Organization v-model="listQuery.departmentId" keyName="id" keyShow="organizationName" placeholder="编报部门" title="部门查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <el-form-item prop="principalUserId" label="项目负责人用户">
          <User v-model="listQuery.principalUserId" keyName="id" keyShow="name" placeholder="用户" title="用户查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">列表详情</div>
        <div>
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
          <el-button type="primary" icon="Edit" :disabled="!checkAuthByCode('')" @click="handleAdd">
            新增
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="arrChangeTreeFn(list)"
              row-key="id"
              fit
              highlight-current-row
              tooltip-effect="dark">
      <el-table-column align="center" width="60px" />
      <el-table-column v-if="isDebug" label="ID" prop="id" width="200px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.id }}</template>
      </el-table-column>
      <el-table-column label="项目分类" prop="catalogId" min-width="170px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ getIdLabel(catalogList, row.catalogId, 'catalogName') }}</template>
      </el-table-column>
      <el-table-column align="center" label="一级项目编号" prop="code" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><CodeTag :code="row.code" /></template>
      </el-table-column>
      <el-table-column align="center" label="一级项目名称" prop="name" min-width="155px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="编报部门" prop="departmentId" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="organizationList" :foreignIds="row.departmentId" :foreignLabel="'organizationName'" /></template>
      </el-table-column>
      <el-table-column align="center" label="项目负责人用户" prop="principalUserId" min-width="140px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="userList" :foreignIds="row.principalUserId" :foreignLabel="'name'" /></template>
      </el-table-column>
      <el-table-column align="center" label="上级一级项目ID" prop="parentId" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ getIdLabel(list, row.parentId, 'code') }}</template>
      </el-table-column>
      <el-table-column align="center" label="金额" prop="amount" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><MoneyTag :money="row.amount" /></template>
      </el-table-column>
      <el-table-column align="center" label="本年度申报金额" prop="currentAmount" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><MoneyTag :money="row.currentAmount" /></template>
      </el-table-column>
      <el-table-column align="center" label="计划开始年度" prop="planStart" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.planStart }}</template>
      </el-table-column>
      <el-table-column align="center" label="计划截止年度" prop="planEnd" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.planEnd }}</template>
      </el-table-column>
      <el-table-column align="center" label="附件ID" prop="attachmentId" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.attachmentId }}</template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('')">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
          <el-button type="primary" link @click="handleAdd1(row)" v-if="!row.parentId">新增下级项目</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID" >
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="项目分类" prop="catalogId">
          <el-select v-model="obj.catalogId" class="m-2" placeholder="请选择" @change="refreshProjectOneList(obj)" width="300px" clearable filterable>
            <el-option v-for="item in catalogList" :key="item.id" :label="`${item.catalogCode} - ${item.catalogName}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="一级项目编号" prop="code">
          <el-input v-model="obj.code" placeholder="自动生成" disabled />
        </el-form-item>
        <el-form-item label="一级项目名称" prop="name">
          <el-input v-model="obj.name" placeholder="请输入一级项目名称，最多输入100个字符" />
        </el-form-item>
        <el-form-item prop="departmentId" label="编报部门">
          <Organization v-model="obj.departmentId" keyName="id" keyShow="organizationName" placeholder="编报部门" title="部门查询" />
        </el-form-item>
        <el-form-item prop="principalUserId" label="项目负责人用户">
          <User v-model="obj.principalUserId" keyName="id" keyShow="name" placeholder="项目负责人用户" title="用户查询" />
        </el-form-item>
        <el-form-item label="上级一级项目" prop="parentId" v-if="type !== 1">
            <el-input v-model="oneProjectName" disabled></el-input>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="obj.amount" placeholder="请输入金额" :precision="2" />
        </el-form-item>
        <el-form-item label="本年度申报金额" prop="currentAmount">
          <el-input-number v-model="obj.currentAmount" placeholder="请输入本年度申报金额" :precision="2" />
        </el-form-item>
        <el-form-item label="计划开始年度" prop="planStart">
          <el-date-picker v-model="obj.planStart"
                          type="year"
                          placeholder="请选择计划开始年度"
                          value-format="YYYY"
                          :disabled-date="disabledDate1" />
        </el-form-item>
        <el-form-item label="计划截止年度" prop="planEnd">
          <el-date-picker v-model="obj.planEnd"
                          type="year"
                          placeholder="请选择计划截止年度"
                          value-format="YYYY"
                          :disabled-date="disabledDate2" />
        </el-form-item>
        <el-form-item label="附件上传" prop="attachmentId">
          <FileUpload :isDrag="true" v-model="fileData"></FileUpload>
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime ? obj.createTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime ? obj.updateTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import {alertErrorMsg, customValidator, arrChangeTreeFn, notifySuccess, getListPageSize} from "@/config/common";
import {getUserId} from "@/config/cookie";
import useUserStore from "@/store/modules/user";
import User from "@/views/components/base/selectUser.vue";
import InputTagDialog from "@/components/InputTag/inputTagDialog.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  catalogId: null, // 项目分类
  departmentId: useUserStore().organization.id, // 编报部门ID
  code: null, // 一级项目编号
  name: null, // 一级项目名称
  principalUserId: getUserId(), // 项目负责人用户
  amount: 0, // 金额
  currentAmount: 0, // 本年度申报金额
  state: null, // 项目库状态
  planStart: null, // 计划开始年度
  planEnd: null, // 计划截止年度
  attachmentId: null, // 附件ID
  parentId: null,
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'projectOne_nocache',
  components: {Organization, SvgIcon, InputTagDialog, User},
  mixins: [baseConfig],
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      radio1: '代办',
      radio2: '已保存',
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      value1: '',
      type: 1,
      oneProjectName: '',
      loading: false,
      list: null,
      listArr: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: getListPageSize(),
        sortField: 'id',
        sortType: 'desc',
        catalogId: null,
        departmentId: useUserStore().organization.organizationType !== '1' ? useUserStore().organization.id : '',
        code: null,
        name: null,
        principalUserId: getUserId(),
        amount: null,
        currentAmount: null,
        state: null,
        planStart: null,
        planEnd: null,
        attachmentId: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        catalogId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '项目分类ID', trigger: ['blur', 'change'] }],
        departmentId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '编报部门ID', trigger: ['blur', 'change'] }],
        code: [{ required: false, validator: customValidator, min: 0, max: 50, label: '一级项目编号', trigger: ['blur', 'change'] }],
        name: [{ required: false, validator: customValidator, min: 0, max: 100, label: '一级项目名称', trigger: ['blur', 'change'] }],
        principalUserId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '项目负责人用户', trigger: ['blur', 'change'] }],
        amount: [{ required: false, validator: customValidator, min: 0, max: 13, label: '金额', trigger: ['blur', 'change'] }],
        currentAmount: [{ required: false, validator: customValidator, min: 0, max: 13, label: '本年度申报金额', trigger: ['blur', 'change'] }],
        state: [{ required: false, validator: customValidator, min: 0, max: 20, label: '项目库状态', trigger: ['blur', 'change'] }],
        planStart: [{ required: false, validator: customValidator, min: 0, max: 4, label: '计划开始年度', trigger: ['blur', 'change'] }],
        planEnd: [{ required: false, validator: customValidator, min: 0, max: 4, label: '计划截止年度', trigger: ['blur', 'change'] }],
        attachmentId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '附件ID', trigger: ['blur', 'change'] }],
      },
      organizationList: initListStore().organizationList,
      governmentList: initListStore().governmentList,
      userList: initListStore().userList,
      catalogList: initListStore().catalogList,
      projectOneList: [],
      fileData: null,
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    this.nameOfPermission = 'projectOne'
    this.getFavorite(this.nameOfPermission)?.then(res => this.userFavorites = res)
    this.getList()
    // this.initList()
  },
  methods: {
    arrChangeTreeFn,
    useUserStore,
    disabledDate1(date) {
      return date.getFullYear() < new Date().getFullYear()
    },
    disabledDate2(date) {
      if (this.obj.planStart) {
        return date.getFullYear() < parseInt(this.obj.planStart)
      } else {
        return date.getFullYear() < new Date().getFullYear()
      }
    },
    // async initList() {
    //   let p1 = doGet(this.svc, '/government/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(this.svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let p3 = doGet(this.svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let p4 = doGet(this.svc, '/budget-catalog/page', {state:'1',pageSize: this.listQuery.pageSize}, false)
    //   let resArray = await Promise.all([p1, p2, p3, p4])
    //   this.governmentList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    //   this.userList = resArray[2]['records']
    //   this.catalogList = resArray[3]['records']
    // },
    refreshProjectOneList(row) {
      this.projectOneList = []
      if (!row)
        return
      row.parentId = null
      if (!row.catalogId)
        return
      doGet(this.svc, '/budget-project-one/page', {catalogId:row.catalogId, pageSize: this.listQuery.pageSize}, false).then(res => {
        this.projectOneList = res['records']
      })
    },
    getList() {
      this.listLoading = true
      doGet(this.svc, '/budget-project-one/page', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.listArr = res['records']
        // this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.type = row.parentId === null ? 1 : 2
      this.dialogType = 'edit'
      this.dialogTypeTitle = '编辑'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, row)
      if (this.type !== 1) {
        let index = this.listArr.findIndex(item => item.id === row.parentId)
        console.log('this.listArr[index]',this.listArr[index])
        this.oneProjectName = this.listArr[index].code + '-' +  this.listArr[index].name
      }
    },
    handleView(row) {
      this.type = row.parentId === null ? 1 : 2
      this.dialogType = 'view'
      this.dialogTypeTitle = '详情'
      this.dialogVisible = true
      this.checkStrictly = false
      this.obj = Object.assign({}, row)
      if (this.type !== 1) {
        let index = this.listArr.findIndex(item => item.id === row.parentId)
        this.oneProjectName = this.listArr[index].code + '-' +  this.listArr[index].name
      }
    },
    handleAdd() {
      this.oneProjectName = ''
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
      this.type = 1
    },
    handleAdd1(row) {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
      this.type = 2
      this.obj.parentId = row.id
      this.obj.catalogId = row.catalogId
      this.oneProjectName = row.code + '-' + row.name
    },
    handleExport() {
      doGetDownload(this.svc, '/budget-project-one/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(this.svc, '/budget-project-one/' + row.id, {}).then(_ => {
        notifySuccess('操作成功')
        this.getList()
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      if (this.fileData) {
        this.obj.attachmentId = this.fileData.id
      }
      switch (this.dialogType) {
        case "add":
          doPost(this.svc, '/budget-project-one/add', this.obj).then(() => {
            notifySuccess('操作成功')
            this.getList()
            this.dialogVisible = false
          })
          break
        case "edit":
          doPut(this.svc, '/budget-project-one/modify', this.obj).then(() => {
            notifySuccess('操作成功')
            this.getList()
            this.dialogVisible = false
          })
          break
      }
    },
  }
}
</script>
<style>
</style>
<style scoped>
</style>
